package com.example.demo.util;

import com.example.demo.common.ConnectionContainer;
import com.example.demo.listen.TxTransactionListen;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.sql.Connection;

/**
 * @author yuaneg 2018/12/12
 */
public class ConnectionProxy implements InvocationHandler {

    private static final String COMMIT = "commit";

    private static final String CLOSE = "close";

    private Connection connection;

    private TxTransactionListen txTransactionListen;

    private String key;

    public ConnectionProxy(Connection connection, TxTransactionListen txTransactionListen, String key) {
        this.connection = connection;
        this.txTransactionListen = txTransactionListen;
        this.key = key;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (COMMIT.equals(method.getName())) {
            txTransactionListen.addConnection(key, new ConnectionContainer(connection, System.currentTimeMillis()));
            return null;
        }
        if (CLOSE.equals(method.getName())) {
            return null;
        }
        return method.invoke(connection, args);
    }
}
